package com.logos.ruralrevitalization.controller;

import com.logos.ruralrevitalization.entity.MessageVO;
import com.logos.ruralrevitalization.repository.ChatHistoryRepository;
import com.logos.ruralrevitalization.result.Result;
import com.logos.ruralrevitalization.utils.TouristLoginUtil;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/ai/history")
public class ChatHistoryController {

    @Resource
    private ChatHistoryRepository chatHistoryRepository;

    @Resource
    private ChatMemory chatMemory;

    @Resource
    private TouristLoginUtil touristLoginUtil;

    /**
     * 查看历史会话列表
     */
    @GetMapping
    public Result<List<String>> getChatIds() {
        String userId = touristLoginUtil.getId();
        List<String> chatIdList = chatHistoryRepository.getChatIdList(userId);
        return Result.ok(chatIdList);
    }

    /**
     * 查看历史会话
     * @param chatId 会话id
     */
    @GetMapping("/{chatId}")
    public Result<List<MessageVO>> getChatHistory(@PathVariable("chatId") String chatId) {
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if (messages == null) {
            return null;
        }
        List<MessageVO> result = messages.stream().map(MessageVO::new).toList();
        return Result.ok(result);
    }
}